using UnityEngine;
using DanielSig;
using DanielSig.UnityExtensions;
using System;
using System.Collections.Generic;

public class PersonalSpace : MonoBehaviour
{
	public float Radius = 1;
	public float Force = 1;
	private static LinkedList<PersonalSpace> _spaces;
	private CharacterController _ctrl;
	private Vector3 _prevPos;
	private float Movement{ get{ return transform.position.DistanceTo(_prevPos); } }
	private float GetMovement(Vector3 direction)
	{
		return (transform.position - _prevPos).Dot(direction);
	}
	public void Start()
	{
		_ctrl = (CharacterController)collider;
		if (_spaces == null)
			_spaces = new LinkedList<PersonalSpace>();
		_spaces.AddLast(this);
		GameCore.Register(UpdatePersonalSpace);
	}
	
	public void OnDestroy()
	{
		_spaces.Remove(this);
		GameCore.Unregister(UpdatePersonalSpace);
	}
	
	public void UpdatePersonalSpace()
	{
		foreach (PersonalSpace s in _spaces)
		{
			if (s == this)
				continue;
						
			float dist = this.transform.position.DistanceTo(s.transform.position);
			if (dist < Radius + s.Radius)
			{
				dist = ((Radius + s.Radius)-dist);
				Vector3 dir = this.transform.position.DirectionTowards(s.transform.position);
				
				float movement1 = this.GetMovement(dir).Abs();
				float movement2 = s.GetMovement(dir).Abs();
				float ratio = movement1 + movement2;
				ratio = ratio > 0 ? movement1 / ratio : 0.5F;
				
				this._ctrl.SimpleMove(-dir * dist * Force * ratio);
				s._ctrl.SimpleMove(dir * dist * Force * (1-ratio));
			}
		}
		_prevPos = transform.position;
	}
}